iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 20
0
影片教學

懶人寫寫 BOT系列 第 20

Day 20 Function - Prevent Side Effect - Clean Code Ruby

  • 分享至 

  • xImage
  •  

嗨,我是 Fly,用 Ruby 寫 Chatbot 並挑戰30天分享心得
為確保不會沒靈感
每日含 Ruby 主題文章增加內容
https://github.com/leo424y/clean-code-ruby

避免副作用

一個變數指一件事,函數作用後是另件事了

Bad:

# Global variable referenced by following function.
# If we had another function that used this name, now it'd be an array and it could break it.
$name = 'Ryan McDermott'

def split_into_first_and_last_name
  $name = $name.split(' ')
end

split_into_first_and_last_name()

puts $name # ['Ryan', 'McDermott']

Good:

def split_into_first_and_last_name(name)
  name.split(' ')
end

name = 'Ryan McDermott'
new_name = split_into_first_and_last_name(name)

puts name # 'Ryan McDermott'
puts new_name # ['Ryan', 'McDermott']

再避免副作用

再次避免搞混變數及函式

Bad:

def add_item_to_cart(cart, item)
  cart.push(item: item, time: Time.now)
end

Good:

def add_item_to_cart(cart, item)
  cart + [{ item: item, time: Time.now }]
end

上一篇
Day 19 - Clean Code Ruby
下一篇
Day 21 Clean Code Ruby
系列文
懶人寫寫 BOT30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言